#!/bin/sh
#desc:Manage cron tasks
#type:local
#package:odcontrol

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later

#TODO Allow other users too
CRONDIR=/etc/crond.d/admin
mkdir -p $CRONDIR

case "$1" in
	"delete")
		if test -f $CRONDIR/$2; then
			rm $CRONDIR/$2
			echo "# Task deleted"
		else
			echo "#ERR task not found"
		fi
	;;

	"save")
		code="$2"
		name="$3"
		period="$4"
		data="$5"
		script="$6"
		params="$7"
		echo "#desc:$name" 		> $CRONDIR/$code
		echo "#period:$period" 	>> $CRONDIR/$code
		echo "#data:$data" 		>> $CRONDIR/$code
		echo "#script:$script" 	>> $CRONDIR/$code
		echo "#params:$params" 	>> $CRONDIR/$code
		# Minute   Hour   Day of Month       Month          Day of Week        Command    
		# (0-59)  (0-23)     (1-31)    (1-12 or Jan-Dec)  (0-6 or Sun-Sat)                
		case $period in
			"daily")
				hour=`echo $data| cut -f1 -d:`
				minute=`echo $data| cut -f2 -d:`
				pattern="$minute $hour * * *"
			;;
			"weekday")
				if test "$data" -gt "-1" && test "$data" -lt "7"; then
					pattern="* * * * $data"
				else
					echo "#ERR Invalid day $data"
				fi
			;;
			"monthday")
				if test "$data" -gt "0" && test "$data" -lt "32"; then
					pattern="* * $data * *"
				else
					echo "#ERR Invalid day $data"
				fi
			;;
			*)
				pattern="* * * * *"
			;;
		esac
		if test -z "$pattern"; then
			echo "#ERR Invalid data"
		else
			if test -f /usr/local/opendomo/$script ; then
				script="/usr/local/opendomo/$script"
			fi
			if test -f /usr/local/bin/$script ; then
				script="/usr/local/bin/$script"
			fi
			echo "$pattern $script $params >/dev/null" >> $CRONDIR/$code
		fi
	;;
	
	*)
		if test -f $CRONDIR/$1; then
			f="$CRONDIR/$1"
			code=$1
			name=`grep desc $f|cut -f2- -d:`
			period=`grep period $f|cut -f2 -d:`
			data=`grep data $f|cut -f2- -d:`
			script=`grep script $f|cut -f2 -d:`
			params=`grep params $f|cut -f2 -d:`
		fi
	;;
esac

cd $CRONDIR

echo "#> Available"
echo "list:`basename $0`"
for task in *; do
	#TODO Add description
	desc=`grep desc $task| cut -f2 -d:`
	test -z "$desc" && desc="$task"
	echo "	-$task	$desc	task"
	if test -z $TASKS; then
		TASKS="$task"
	else
		TASKS="$TASKS,$task"
	fi
done
echo "actions:"
cd /usr/local/opendomo/
SCRIPTS="@scripts:Scripts"
for s in *; do
	desc=`grep '#desc:' $s | cut -f2 -d:`
	if test -z "$desc"; then
		desc="$s"
	fi
	SCRIPTS="$SCRIPTS,$s:$desc"
done
#SCRIPTS=`echo *|sed 's/ /,/g'`
echo
echo "#> New"
echo "form:`basename $0`"
echo "	action	action	hidden	save"
echo "	task	Code	text:[a-z0-9]+	$code"
echo "	desc	Name	text:[a-zA-Z0-9 ]+	$name"
echo "	period	Period	list[daily,weekday,monthday]	$period"
echo "	data	Data	text:[0-9:]+	$data"
echo "	script	Script	list[$SCRIPTS]	$script"
echo "	params	Params	text	$params"
echo "actions:"
echo 
if ! test -z "$TASKS"; then
	echo "#> Remove"
	echo "form:`basename $0`"
	echo "	action	action	hidden	delete"
	echo "	task	Task	list[$TASKS]"
	echo "actions:"
	echo
fi
